# -*- coding:utf-8 -*-
# __author__ : "徐川东"
# Date: 2020/9/8 10:35
# File: workdcorator.py
# IDE: PyCharm
from functools import wraps
from utils import common
import datetime
from models.userlogs import UserLogs
from django.contrib.auth.models import AnonymousUser
from utils.response import httpstate
from rest_framework.request import Request
from django.http import HttpRequest


class WorkDecorator(object):
    """
    操作日志装饰器
    """

    def __init__(self, operate='', message=''):
        self._message = message
        self._operate = '查看' if operate == '' else operate

    def __call__(self, func):

        self.flag = False

        @wraps(func)
        def wrapped_function(view, *args, **kwargs):

            if len(args) <= 0:
                return func(view, *args, **kwargs)
            request = args[0]

            if not isinstance(request, Request) and not isinstance(request, HttpRequest):
                return func(view, *args, **kwargs)

            if request.META.get('HTTP_X_FORWARDED_FOR'):
                ip = request.META.get("HTTP_X_FORWARDED_FOR")
            else:
                ip = request.META.get("REMOTE_ADDR")

            # print("ip : ", ip)
            url = f"http://{request.get_host()}{request.get_full_path()}"
            # print(func.__doc__)
            # 拿到操作详情
            if func.__doc__ and self._message == '':
                self._message = func.__doc__
            elif self._message == "":
                self._message == f"接口{url}"

            # 从请求参数中获取操作类型
            if self._operate == "查看":
                if "operate" in request.GET:
                    self._operate = request.GET.get("operate")
                elif "operate" in request.POST:
                    self._operate = request.POST.get("operate")
                elif "operate" in request.data:
                    self._operate = request.POST.get("operate")

            # 写入日志

            if not isinstance(request.user, AnonymousUser):
                pass
                # 操作前日志记录
            else:
                self.flag = True
            # 执行方法
            result = func(view, *args, **kwargs)

            # 写入登录日志
            if result.data['code'] == httpstate.CODE_SUCCESS and 'Auths' in url:
                if self.flag:
                    # 登录成功 单独写 登录日志   因为request里面没有user
                    operate_log = UserLogs(
                        user_id=result.data['data']['id'],
                        module='登录系统',
                        ip=ip,
                    )
                    operate_log.save()
            elif result.data['code'] == httpstate.CODE_SUCCESS:
                self.write_operate_log(request, operate=self._operate, message=self._message, )
            return result

        return wrapped_function

    @staticmethod
    def write_operate_log(request, operate, message):
        """
        写入日志
        @param request:  http_request  获取请求ip
        @param operate: 操作类别
        @param message: 操作详情
        @return:
        """

        if request.META.get('HTTP_X_FORWARDED_FOR'):
            ip = request.META.get("HTTP_X_FORWARDED_FOR")
        else:
            ip = request.META.get("REMOTE_ADDR")

        url = f"http://{request.get_host()}{request.get_full_path()}"

        if not operate:
            operate = ""
        if not message:
            message = ""
        user_id=0
        try:
            user_id=request.user['id']
        except :
            print('匿名调用接口')
        operate_log = UserLogs(
            user_id=user_id,
            module=operate,
            function=message,
            ip=ip
        )
        operate_log.save()

